<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");

class GjdztypeModel extends Model {
    //表字段配置
    protected $fields   = array(
                                'gjdztype_id',
                                'gjdztype_name',
                                'sort_loc',
                                'jump_url',
                                'gjdztype_res',
                                'gjdztype_rule',
                                'gjdztype_price',
                                'gjdztype_desc',
                                'image_path',
                                'edit_time',
                                '_pk' => 'gjdztype_id',
                                '_autoinc' => true
                            );
    
    //自动验证
    protected $_validate    = array(
        array('gjdztype_name', 'require', '名称不能为空！'),
        array('sort_loc', 'number', '排序编号必须是数字！',2),
        array('jump_url', 'url', '跳转链接无效！',2)
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function')
    );

    protected static $orderFields = 'sort_loc';

    protected static $xmlFields   = '`gjdztype_id`, `gjdztype_name`, `image_path`, `gjdztype_res`, `gjdztype_rule`, `gjdztype_price`, `gjdztype_desc`, `jump_url`';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    protected $_countWhere;

    protected $_error;
    protected $_gjdz;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 101, 'h' => 74, 't' => 'jpg', 'i' => true)
    );

    //XML配置参数
    protected static $xmlFilePath   = 'xml/gjdztype.xml';

    protected static $childNode     = '
    <asset small="%s" large="%s" url="%s">
		<description><![CDATA[%s]]></description>
    </asset>
    ';
    protected static $rootNode     = '<gallery fullScreenImages="no">
    %s
</gallery>';


    public function __construct() {
        parent::__construct();

        $this->_countWhere  = '';
        $this->_imageSize   = 2;
        $this->_gjdz        = null;
        $this->_imageTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
        $this->_uploadDir   = 'Public/default/uploadfiles/gjdz';
        $this->_error       = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchGjdztype($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`gjdztype_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`gjdztype_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeGjdztype($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeGjdztype($page = 0, $whereGjdztype = '', $perPage = 10) {
       return $this->where($whereGjdztype)->order('sort_loc')->limit($perPage)->page($page)->select();
    }

//查看列表方法 
    public function seeallGjdztype($whereGjdztype = '') {
        $list    = $this->field('`gjdztype_id`,`gjdztype_name`')->where($whereGjdztype)->order(self::$orderFields)->select();

        return $list;
    }

    //查看记录详细信息方法
    public function infoGjdztype($recordId) {
        $record     = $this->where('`gjdztype_id` = ' . $recordId)->find();
        if(!empty($record['image_path'])) {
            $record['image_path_small']     = $this->genThumbImageName($record['image_path']) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
        }

        return $record;
    }

    //编辑记录方法
    public function editGjdztype($recordId) {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(isset($_POST['del_image'])) {
            if(!empty($_POST['del_image'])) {
                if(false === $this->deleteFile($_POST['old_image_path'])) {
                    Logger::log('删除文件失败！' . $_POST['old_image_path']);
                } else {
                    $_POST['image_path']= '';
                }
            } else {
                $_POST['image_path']    = $_POST['old_image_path'];
            }
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->save()) {
            return $this->getError();
        }
        $this->syncGjdz();

        return true;
    }

    //同步高级定制对应的详细部分
    protected function syncGjdz() {
        $gjdz   = D('Gjdz');
        $gjdz->syncGjdzinfo($recordId, $_POST);
    }

    //添加记录方法
    public function addGjdztype() {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //删除记录方法
    public function deleteGjdztype($recordId) {
        return $this->quickDeleteGjdztype(array($recordId));
    }

    //快捷操作：删除记录
    public function quickDeleteGjdztype(array $recordIds){
        $this->quickDeleteImageGjdztype($recordIds);
        $whereStr   = $this->genWhereIn('gjdztype_id', $recordIds);

        return $this->where($whereStr)->delete();
    }

    //快捷操作：删除记录相关文件
    public function quickDeleteImageGjdztype(array $recordIds) {
        $whereStr   = $this->genWhereIn('gjdztype_id', $recordIds) . ' AND (`image_path` !=\'\' AND `image_path` IS NOT NULL)';
        $recordList = $this->where($whereStr)->field('gjdztype_id, image_path')->select();
        if(empty($recordList)) {
            return ture;
        }
        $whereStr   = '`gjdztype_id` IN (';
        foreach($recordList as $record) {
            if($this->deleteFile($record['image_path'])) {
                $whereStr   .= $record['gjdztype_id'] . ', ';
            }
        }
        $whereStr    .= '-1)'; 

        return $this->where($whereStr)->setField('image_path', '');
    }

    //生成FLASH调用的XML文件
    public function xmlGjdztype() {
        $perPage        = 10;
        $totalRows      = $this->getCountRecords();
        $totalPage      = ceil($totalRows / $perPage);
        for($page = 0; $page < $totalPage; $page ++) {
            $recordList     = $this->getXmlRecordList($page, $perpage);
            $xmlContent     .= $this->genXmlContent($recordList);
        }
        if(false === $this->writeXml($xmlContent)) {
            Logger::log('写入XML内容失败！' . __CLASS__);
        }

        return true;
    }

    //得到XML的数据集
    protected function getXmlRecordList($page, $perpage = 10) {
        return $this->field(self::$xmlFields)->order(self::$orderFields)->page($page, $perpage)->select();
    }

    //写入XML文件内容
    protected function writeXml($xmlContent) {
        $xmlContent     = sprintf(self::$rootNode, $xmlContent);
        $xml    = new Xml(self::$xmlFilePath, $xmlContent);

        return  $xml->save();

    }

    //生成主页的XML内容
    protected function genXmlContent($recordList) {
        if(empty($recordList)) {
            return '';
        }
        foreach($recordList as $record) {
            $xmlContent .= vsprintf(self::$childNode, $this->getXmlData($record));
            $this->genGjdzXmlContent($record['gjdztype_id']);
        }

        return $xmlContent;
    }
    
    //得到需要的XML数据
    protected function getXmlData($record) {
        if(!empty($record['image_path'])) {
            $thumbImgPath           = $this->getThumbImagePath($record['image_path']);
            $record['image_path']   = $this->_uploadDir . '/' . $record['image_path'];
            $xmlData[]              = $thumbImgPath;
        } else {
            $xmlData[]              = '';
        }
        $xmlData[]              = $record['image_path'];
        $xmlData[]              = $record['jump_url'];
        $xmlData[]              = $record['gjdztype_desc'];

        return $xmlData;
    }

    //生成当前高级定对应的所有详细产品XML文件信息
    protected function genGjdzXmlContent($gjdzId) {
        if(empty($gjdzId)) {
            return false;
        }
        $this->_gjdz     = $this->getGjdzObject();
        if(true == $this->_gjdz->xmlGjdz($gjdzId)) {
            Logger::log("生成高级定制：" . $gjdzId . "对应的详细高级产品XML信息成功！");
            return true;
        }
        
        Logger::log("生成高级定制：" . $gjdzId . "对应的详细高级产品XML信息失败！");
        return false;
    }

    //得到详细高级定制对象
    protected function getGjdzObject() {
        if(!empty($this->_gjdz)) {
            return $this->_gjdz;
        }

        return D('Gjdz');
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //上传文件方法
    protected function uploadFile() {
        if(!empty($_FILES['image_path']['name'])) {
            $uploadFile     = new UploadFile($_FILES['image_path'],
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                return false;
            }
            $arrPath    = explode('/', $uploadFile->getUploadFilePath());
            $_POST['image_path']    = array_pop($arrPath);
            $_POST['image_path']    = array_pop($arrPath) . '/' . $_POST['image_path'];
            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return true;
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //得到缩略图路径
    public function getThumbImagePath($srcFilePath) {
       return $this->_uploadDir . '/' . $this->genThumbImageName($srcFilePath) . '_s.' . self::$thumbImgInfo['_s']['t'];
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath, $this->_uploadDir);
        } 
    }

    public function getUploadDir() {
        return preg_replace('/public/i', '', $this->_uploadDir);
    }

    //得到模块的类型ID
    public function getModelTypeId() {
        if(empty($this->_modelTypeId)) {
            return $_GET['type'];
        }

        return $this->_modelTypeId;
    }

}

?>
